﻿Imports System.Net.Mail
Partial Class WebForm_ManageWorkHeader_HandleWorkHeader
    Inherits System.Web.UI.UserControl
    Public rboOther As String = "9" '髒亂地區類別(其他)
    Public gvDirtyItemID As String = "7" '髒亂種類/程度(其他)

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub ddlStatus_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        If TryCast(sender, DropDownList).SelectedValue = "T" Or TryCast(sender, DropDownList).SelectedValue = "RG" Then
            TryCast(fv.FindControl("ddlChangeOrganizationID"), DropDownList).Visible = True
        Else
            TryCast(fv.FindControl("ddlChangeOrganizationID"), DropDownList).Visible = False
        End If
        TryCast(fv.FindControl("ddlChangeOrganizationID"), DropDownList).SelectedIndex = -1
    End Sub

    Protected Sub fv_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles fv.DataBound
        If Me.fv.DataItem IsNot Nothing Then
            Me.BindSendMail()
            Me.BindStatus()
            Me.BindChangeOrganization()

            TryCast(Me.fv.FindControl("lbtnUploadA"), LinkButton).Attributes("onclick") = Me.UploadString(DataBinder.Eval(Me.fv.DataItem, "CasePassword"), "PictureA")
            TryCast(Me.fv.FindControl("lbtnUploadB"), LinkButton).Attributes("onclick") = Me.UploadString(DataBinder.Eval(Me.fv.DataItem, "CasePassword"), "PictureB")
            '髒亂地點
            TryCast(fv.FindControl("lblLocationValue"), Label).Text = DataBinder.Eval(Me.fv.DataItem, "RegionName")
            TryCast(fv.FindControl("lblLocationValue"), Label).Text &= DataBinder.Eval(Me.fv.DataItem, "RoadName")
            TryCast(fv.FindControl("lblLocationValue"), Label).Text &= DataBinder.Eval(Me.fv.DataItem, "RoadItemName")
            TryCast(fv.FindControl("lblLocationValue"), Label).Text &= DataBinder.Eval(Me.fv.DataItem, "Location")

            '有登入則顯示案件編號;沒登入則顯示案件代碼
            If Me.Page.User.Identity.Name <> "" Then
                TryCast(Me.fv.FindControl("trRandomCasePassword"), HtmlTableRow).Visible = False
            Else
                TryCast(Me.fv.FindControl("trCasePassword"), HtmlTableRow).Visible = False
            End If

            '判斷是否可處理案件
            If Me.IsClose Then '已結案案件
                If Me.MyType = "1" Then
                    '環保局人員有退件功能
                    TryCast(fv.FindControl("btnHandle"), Button).Visible = True
                End If
            Else '待處理案件
                If Me.MyType = "2" Or Me.MyType = "3" Then
                    TryCast(fv.FindControl("btnHandle"), Button).Visible = True
                End If
            End If

            '繫結髒亂種類
            Me.BindDirtyItemForEdit(FindDirtyHeaderID)

            '處理記錄
            Me.BindActionRecord()
        End If

    End Sub

    Protected Sub fv_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewCommandEventArgs) Handles FV.ItemCommand
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        Dim dt As New Data.DataTable

        If e.CommandName = "btnBack" Then
            RaiseEvent Back(Me, New EventArgs)
        ElseIf e.CommandName = "btnHandle" Then
            TryCast(Me.fv.FindControl("divHandleDataInsert"), HtmlControls.HtmlGenericControl).Visible = True
            TryCast(Me.fv.FindControl("btnHandle"), Button).Visible = False
        ElseIf e.CommandName = "btnCancel" Then
            TryCast(Me.fv.FindControl("divHandleDataInsert"), HtmlControls.HtmlGenericControl).Visible = False
            TryCast(Me.fv.FindControl("btnHandle"), Button).Visible = True
        ElseIf e.CommandName = "btnUpdate" Then
            '條件判斷
            If TryCast(Me.fv.FindControl("ddlStatus"), DropDownList).SelectedValue = "F" Then
                '案件處理完成需要上傳處理前後的照片
                sql.Length = 0
                sql.AppendFormat("select a.* from FD_FindDirtyHeader a")
                sql.AppendFormat(" where a.FindDirtyHeaderID='{0}' ", Me.FindDirtyHeaderID)
                sql.AppendFormat(" and a.CasePassword in (select CasePassword from FD_UploadFile where UploadType='PictureA')")
                sql.AppendFormat(" and a.CasePassword in (select CasePassword from FD_UploadFile where UploadType='PictureB')")
                dt = dat.GetData(sql)
                If Not dt.Rows.Count > 0 Then
                    MyObj.ShowMessage(Me.GetLocalResourceObject("NeedPicture"))
                    Return
                End If
            ElseIf TryCast(Me.fv.FindControl("ddlStatus"), DropDownList).SelectedValue = "T" Or TryCast(Me.fv.FindControl("ddlStatus"), DropDownList).SelectedValue = "RG" Then
                '轉件時需選擇轉件單位
                If TryCast(Me.fv.FindControl("ddlChangeOrganizationID"), DropDownList).SelectedValue = "" Then
                    MyObj.ShowMessage(Me.GetLocalResourceObject("NeedChangeOrganization"))
                    Return
                End If
            End If

            If Me.UpdateData = True Then
                If Me.NeedSendMail Then
                    Dim strScript As String = "window.showModalDialog('" & Me.ResolveUrl("~/WebForm/SelfManageWorkHeader/SendMail.aspx")
                    strScript &= "?CasePassword=" & Me.CasePassword & "&thetime=" & DateTime.Now.ToString("hhmmss") & "', 'SendMail', 'dialogHeight:500px;dialogWidth:800px;status:no,resizable:no,scrollbars:auto,toolbar:no,location:no,menubar:no;');"
                    ScriptManager.RegisterClientScriptBlock(TryCast(HttpContext.Current.Handler, Page), GetType(String), strScript, strScript, True)
                Else
                    MyObj.ShowMessage(Me.GetLocalResourceObject("SaveData_Success"))
                End If
                RaiseEvent Finish(Me, New EventArgs)
            End If
        End If
    End Sub

End Class

Partial Class WebForm_ManageWorkHeader_HandleWorkHeader

#Region "初始化資料"
    '編輯
    Public Sub InitData(ByVal FindDirtyHeaderID As String, ByVal Status As String)
        Me.FindDirtyHeaderID = FindDirtyHeaderID
        Me.MyOrganizationID = clsAuth.GetOrganizationID(clsAuth.GetUserID())

        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        Dim dt As New Data.DataTable

        sql.AppendFormat("select a.*,b.RegionName,c.RoadItemName ")
        sql.AppendFormat(" ,Case a.RegionType when '{0}' then '' else d.RoadName end as RoadName", "道路")
        sql.AppendFormat(" from FD_FindDirtyHeader a")
        sql.AppendFormat(" Join Region b on a.TownID=b.RegionID")
        sql.AppendFormat(" left Join FD_RoadItem c ")
        sql.AppendFormat(" on c.RoadItemID = a.RoadItemID")
        sql.AppendFormat(" left Join RegionRoad d ")
        sql.AppendFormat(" on d.RoadID = a.VillageID")
        sql.AppendFormat(" where a.FindDirtyHeaderID='{0}' ", FindDirtyHeaderID)

        MyObj.SetDateLocale("zh-TW")
        dt = dat.GetData(sql)
        Me.fv.DataSource = dt
        Me.fv.DataBind()
        MyObj.SetDateLocale("")
    End Sub

#End Region

#Region "繫結資料"
    Private Sub BindDirtyItemForEdit(ByVal FindDirtyHeaderID As String)
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.AppendFormat("Select * from FD_FindDirtyItem")
        sql.AppendFormat(" where FindDirtyHeaderID='{0}' ", FindDirtyHeaderID)

        Dim dt As Data.DataTable = dat.GetData(sql)

        Dim lblDirtyItemValue As Label = TryCast(Me.fv.FindControl("lblDirtyItemValue"), Label)
        For j As Integer = 0 To dt.Rows.Count - 1
            If lblDirtyItemValue.Text <> "" Then
                lblDirtyItemValue.Text &= "、"
            End If
            lblDirtyItemValue.Text &= dt.Rows(j)("DirtyItemName")
        Next
    End Sub

    '處理紀錄
    Private Sub BindActionRecord()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        sql.Length = 0
        sql.AppendFormat("select a.*,b.OrganizationName,c.Text as StatusText from FD_ActionRecord a ")
        sql.AppendFormat("left join Organization b on a.OrganizationID=b.OrganizationID ")
        sql.AppendFormat("left Join FD_CodeMapping c on a.Status=c.Value and c.TableName='FindDirtyHeader' and c.ColumnName='Status' and c.Active='Y' ")
        sql.AppendFormat("where a.CasePassword='{0}' ", Me.CasePassword)
        sql.AppendFormat("and a.Active='{0}' ", "N")
        sql.AppendFormat("order by UpdateDate ")

        Dim gvActionRecord As GridView = TryCast(Me.fv.FindControl("gvActionRecord"), GridView)
        MyObj.SetDateLocale("zh-TW")
        gvActionRecord.DataSource = dat.GetData(sql)
        gvActionRecord.DataBind()
        MyObj.SetDateLocale("")
    End Sub

    Private Sub BindSendMail()
        Dim item As RadioButtonList = TryCast(Me.fv.FindControl("rbtlSendMail"), RadioButtonList)

        item.DataTextField = "Text"
        item.DataValueField = "Value"
        item.DataSource = MyObj.GetCodeMappingData("FindDirtyHeader", "SendMail")
        item.DataBind()

        MyObj.MatchItem(item, "Y")
    End Sub

    Private Sub BindStatus()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        sql.AppendFormat("select * from FD_CodeMapping ")
        sql.AppendFormat("where TableName='FindDirtyHeader' and ColumnName='Status' and Value<>'P' ")

        If Me.MyType = "1" Then '環保局人員只有退件功能
            sql.AppendFormat("and Value='RG' ")
        Else
            sql.AppendFormat("and Value<>'RG' ")
        End If
        sql.AppendFormat("order by Sequence ")

        Me.ddlStatus.DataTextField = "Text"
        Me.ddlStatus.DataValueField = "Value"
        Me.ddlStatus.DataSource = dat.GetData(sql)
        Me.ddlStatus.DataBind()

        Me.ddlStatus.Items.Insert(0, MyObj.GetDDLPleaseChooseItem())
    End Sub

    Private Sub BindChangeOrganization()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.AppendFormat("select b.OrganizationId as Value,b.OrganizationName as Text from FD_OrganizationRegionMapping a ")
        sql.AppendFormat("join Organization b on a.OrganizationId=b.OrganizationId ")
        sql.AppendFormat("and b.Active='Y' ")
        'sql.AppendFormat("and a.RegionID<>'TPC' ")
        sql.AppendFormat("where a.OrganizationID<>'{0}' ", MyOrganizationID)
        sql.AppendFormat("order by b.Sequence ")
        Dim dt As Data.DataTable = dat.GetData(sql)

        Dim item As DropDownList = TryCast(Me.fv.FindControl("ddlChangeOrganizationID"), DropDownList)

        item.DataTextField = "Text"
        item.DataValueField = "Value"
        item.DataSource = dt
        item.DataBind()

        item.Items.Insert(0, Me.GetLocalResourceObject("ToOrganization"))
    End Sub

#End Region

#Region "方法"
    '更新
    Private Function UpdateData() As Boolean
        Dim dat As New clsData
        Dim sql As New StringBuilder

        Using scope As New Transactions.TransactionScope
            '更新案件資料FindDirtyHeader
            sql.Length = 0
            sql.AppendFormat("Update FD_FindDirtyHeader set ")
            sql.AppendFormat("Status='{0}' ", Me.Status)
            sql.AppendFormat(",HandleDate='{0:yyyy/MM/dd}' ", Me.HandleDate)
            sql.AppendFormat(",Memo='{0}' ", Me.Memo)
            sql.AppendFormat(" where CasePassword='{0}' ", Me.CasePassword)
            dat.AccData(sql)

            '更新處理資料FD_ActionRecord
            sql.Length = 0
            sql.AppendFormat("Update FD_ActionRecord set ")
            sql.AppendFormat("HandleDate='{0}' ", Me.HandleDate)
            sql.AppendFormat(",Comment='{0}' ", Me.Memo)
            sql.AppendFormat(",Status='{0}' ", Me.Status)
            sql.AppendFormat(",Active='{0}' ", "N")
            sql.AppendFormat(",UpdateBy='{0}' ", clsAuth.GetUserID())
            sql.AppendFormat(",UpdateDate=getdate() ")
            sql.AppendFormat(" where CasePassword='{0}' ", Me.CasePassword)
            sql.AppendFormat(" and OrganizationID='{0}' ", Me.MyOrganizationID)
            sql.AppendFormat(" and Active='{0}' ", "Y")
            dat.AccData(sql)

            '如果有轉派或退件,則新增一筆處理資料到FD_ActionRecord
            If Me.Status = "T" Or Me.Status = "RG" Then
                sql.Length = 0
                sql.AppendFormat("Insert into FD_ActionRecord (CasePassword,OrganizationID ")
                sql.AppendFormat(",Status,Active,CreateBy,CreateDate) select")
                sql.AppendFormat(" '{0}' ", Me.CasePassword)
                sql.AppendFormat(",'{0}' ", Me.ChangeOrganizationID)
                sql.AppendFormat(",'{0}' ", Me.Status)
                sql.AppendFormat(",'{0}' ", "Y")
                sql.AppendFormat(",'{0}' ", clsAuth.GetUserID())
                sql.AppendFormat(",getdate() ")
                dat.AccData(sql)
            End If

            scope.Complete()
        End Using

        Return True
    End Function

    '寄信通知公所及工務段
    Private Function SendMail(ByVal OrganizationName As String, ByVal Email As String)
        Try
            Dim objSMTP As New SmtpClient()
            Dim objMailMessage As New MailMessage()
            Dim SentContent As String = ""
            SentContent = OrganizationName & " 您好："
            SentContent &= "<br>" & "<br>" & "案件編號：" & Me.CasePassword
            SentContent &= "<br>" & "通報日期：" & TryCast(Me.fv.FindControl("lblReportDateValue"), Label).Text
            SentContent &= "<br>" & "地點：" & TryCast(Me.fv.FindControl("lblLocationValue"), Label).Text
            SentContent &= "<br>" & "主旨：" & TryCast(Me.fv.FindControl("lblTopicValue"), Label).Text
            SentContent &= "<br>" & "髒亂描述：" & TryCast(Me.fv.FindControl("lblDescriptionValue"), Label).Text
            'SentContent &= "<br>" & "髒亂種類：" & TryCast(Me.fv.FindControl("lblDirtyItemValue"), Label).Text
            SentContent &= "<br>" & "<br>" & "請盡速前往處理!!謝謝!!"
            SentContent &= "<br>" & "台北縣環保局  敬上"

            objMailMessage.From = New MailAddress(MyObj.GetParameter("Home", "MailSender"))
            objMailMessage.To.Add(New MailAddress(Email))
            objMailMessage.Subject = "台北縣環保局環境污染通報系統通知"
            objMailMessage.SubjectEncoding = System.Text.Encoding.UTF8
            objMailMessage.Body = SentContent
            objMailMessage.BodyEncoding = System.Text.Encoding.UTF8
            objMailMessage.IsBodyHtml = True
            objSMTP.Send(objMailMessage)
            Return True
        Catch ex As Exception
            MyObj.WriteLog(ex.ToString())
            Return False
        End Try
    End Function

    '上傳頁面
    Private Function UploadString(ByVal strID, ByVal strType) As String
        Dim ReturnString As String = ""
        ReturnString = "window.showModalDialog('" & Me.ResolveUrl("~/Public/UploadFile.aspx") & "?CasePassword=" & strID & "&UploadType=" & strType & "&thetime=" & DateTime.Now.ToString("hhmmss") & "', 'UploadFile', 'dialogHeight:500px;dialogWidth:800px;status:no,resizable:no,scrollbars:auto,toolbar:no,location:no,menubar:no;'); return false;"
        Return ReturnString
    End Function
#End Region

#Region "屬性"
    '是否結案
    Public Property IsClose() As Boolean
        Get
            Return ViewState("IsClose")
        End Get
        Set(ByVal value As Boolean)
            ViewState("IsClose") = value
        End Set
    End Property

    Public Property DataAccessMode() As My.DataAccessMode
        Get
            Return ViewState("DataAccessMode")
        End Get
        Set(ByVal value As My.DataAccessMode)
            ViewState("DataAccessMode") = value
        End Set
    End Property

    Public Property FindDirtyHeaderID() As String
        Get
            Return ViewState("FindDirtyHeaderID")
        End Get
        Set(ByVal value As String)
            ViewState("FindDirtyHeaderID") = value
        End Set
    End Property

    '案件編號
    Public ReadOnly Property CasePassword() As String
        Get
            Return TryCast(Me.fv.FindControl("lblCasePasswordValue"), Label).Text
        End Get
    End Property

    'SendMail
    Public ReadOnly Property NeedSendMail() As Boolean
        Get
            'Return TryCast(Me.fv.FindControl("chkSendMail"), CheckBox).Checked
            If TryCast(Me.fv.FindControl("rbtlSendMail"), RadioButtonList).SelectedValue = "Y" And TryCast(Me.fv.FindControl("lblCreateEmailValue"), Label).Text <> "" Then
                Return True
            Else
                Return False
            End If
        End Get
    End Property

    'Status
    Public ReadOnly Property Status() As String
        Get
            Return TryCast(Me.fv.FindControl("ddlStatus"), DropDownList).SelectedValue
        End Get
    End Property

    'HandleDate
    Public ReadOnly Property HandleDate() As String
        Get
            Return TryCast(Me.fv.FindControl("txtHandleDate"), TextBox).Text
        End Get
    End Property

    'Memo
    Public ReadOnly Property Memo() As String
        Get
            Return TryCast(Me.fv.FindControl("txtMemo"), TextBox).Text
        End Get
    End Property

    '轉件單位
    Public ReadOnly Property ChangeOrganizationID() As String
        Get
            Return TryCast(Me.fv.FindControl("ddlChangeOrganizationID"), DropDownList).SelectedValue
        End Get
    End Property

    '登入者組織編號
    Public Property MyOrganizationID() As String
        Get
            Return ViewState("MyOrganizationID")
        End Get
        Set(ByVal value As String)
            ViewState("MyOrganizationID") = value
        End Set
    End Property

    '判斷登入者組織
    Public Property MyType() As String
        Get
            Return ViewState("MyType")
            '1:環保局
            '2:公所
            '3:工務段
        End Get
        Set(ByVal value As String)
            ViewState("MyType") = value
        End Set
    End Property

    '處理單位的案件狀態
    Public Property OriginalStatus() As String
        Get
            Return ViewState("OriginalStatus")
        End Get
        Set(ByVal value As String)
            ViewState("OriginalStatus") = value
        End Set
    End Property
#End Region

#Region "Raise事件"
    Public Event Back(ByVal sender As Object, ByVal e As EventArgs)
    Public Event Finish(ByVal sender As Object, ByVal e As EventArgs)
#End Region
End Class